<template>
  <nut-popup 
    :visible="visible" 
    position="bottom" 
    :style="{ height: '80%' }"
    @close="handleClose"
  >
    <view class="directory-popup">
      <view class="popup-header">
        <text class="popup-title">{{ currentStep === 'hospital' ? '选择医院' : title }}</text>
        <view class="close-btn" @click="handleClose">
          <text>✕</text>
        </view>
      </view>
      
      <view class="popup-content">
        <!-- 医院选择步骤 -->
        <view v-if="showHospital && currentStep === 'hospital'" class="hospital-selection">
          <view v-if="hospitalLoading" class="loading-container">
            <text class="loading-text">正在加载医院列表...</text>
          </view>
          <view v-else-if="hospitalList.length === 0" class="empty-container">
            <text class="empty-text">暂无医院数据</text>
          </view>
          <view v-else class="hospital-list">
            <view 
              v-for="hospital in hospitalList" 
              :key="hospital.id || hospital.key"
              class="hospital-item"
              :class="{ 'selected': isHospitalSelected(hospital) }"
              @click="selectHospital(hospital)"
            >
              <view class="hospital-info">
                <text class="hospital-name">{{ hospital.name || hospital.title }}</text>
                <text class="hospital-address">{{ hospital.address || '地址信息' }}</text>
              </view>
              <view v-if="isHospitalSelected(hospital)" class="selected-icon">
                <IconFont name="Check" size="20" color="#3b82f6" />
              </view>
            </view>
          </view>
        </view>
        
        <!-- 科室选择步骤 -->
        <view v-else-if="currentStep === 'department'">
          <ThreeLevelDirectory 
            ref="directoryRef"
            :sys-org-code="selectedHospital?.sysOrgCode"
            @change="onDirectoryChange">
            
            <!-- 内容插槽 -->
            <template #content="{ currentItem }">
              <view v-if="loading" class="text-center text-gray-500 py-8">
                <text>加载中...</text>
              </view>
              
              <view v-else-if="currentItem" class="selection-info">
                <!-- <view class="selected-item">
                  <text class="text-lg font-bold">{{ currentItem.name }}</text>
                  <text class="text-sm text-gray-500">点击确认选择此科室</text>
                </view> -->
              </view>
              
              <view v-else class="text-center text-gray-500 py-8">
                <text>请选择三级目录项</text>
              </view>
            </template>
          </ThreeLevelDirectory>
        </view>
      </view>
      
      <!-- 固定在底部的确认按钮 -->
      <view class="popup-footer" v-if="canConfirm">
        <nut-button 
          type="primary" 
          class="confirm-btn"
          @click="handleConfirm"
        >
          {{ confirmText }}
        </nut-button>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
// @ts-ignore
import ThreeLevelDirectory from './ThreeLevelDirectory.vue'
import { request } from '@/service/request'

interface Props {
  /** 弹窗显示状态 */
  visible: boolean
  /** 弹窗标题 */
  title?: string
  /** 确认按钮文字 */
  confirmText?: string
  /** 加载状态 */
  loading?: boolean
  /** 是否显示医院选择 */
  showHospital?: boolean
  sysOrgCode?: string
}

interface Emits {
  /** 更新visible状态事件，用于支持v-model */
  (e: 'update:visible', value: boolean): void
  /** 关闭弹窗事件 */
  (e: 'close'): void
  /** 确认选择事件 */
  (e: 'confirm', data: {
    currentItem: any
    level1Item: any
    level2Item: any
    hospital?: any
  }): void
  /** 目录选择变化事件 */
  (e: 'change', data: {
    currentItem: any
    level1Item: any
    level2Item: any
    hospital?: any
  }): void
}

const props = withDefaults(defineProps<Props>(), {
  title: '选择科室',
  confirmText: '确认选择',
  loading: false,
  showHospital: false
})

const emit = defineEmits<Emits>()

// 目录组件引用
const directoryRef = ref()

// 当前步骤：'hospital' | 'department'
const currentStep = ref<'hospital' | 'department'>('hospital')

// 医院相关状态
const hospitalList = ref<any[]>([])
const selectedHospital = ref<any>(null)
const hospitalLoading = ref(false)

// 当前选中的项目
const currentSelectedItem = ref(null)
const currentLevel1Item = ref(null)
const currentLevel2Item = ref(null)

// 计算属性：是否可以确认
const canConfirm = computed(() => {
  if (props.showHospital && currentStep.value === 'hospital') {
    return selectedHospital.value !== null
  } else if (currentStep.value === 'department') {
    return currentSelectedItem.value !== null
  }
  return false
})

/**
 * 判断医院是否被选中
 */
const isHospitalSelected = (hospital: any) => {
  if (!selectedHospital.value) return false
  
  // 使用字符串比较来避免 Proxy 对象比较问题
  const selectedKey = String(selectedHospital.value.key || '')
  const currentKey = String(hospital.key || '')
  const selectedId = String(selectedHospital.value.id || '')
  const currentId = String(hospital.id || '')
  
//   console.log('比较医院:', {
//     selectedKey,
//     currentKey,
//     selectedId,
//     currentId,
//     keyMatch: selectedKey === currentKey && selectedKey !== '',
//     idMatch: selectedId === currentId && selectedId !== ''
//   })
  
  // 优先使用 key 比较（因为从日志看 key 是主要标识符）
  if (selectedKey && currentKey && selectedKey === currentKey) {
    return true
  }
  
  // 其次使用 id 比较
  if (selectedId && currentId && selectedId === currentId) {
    return true
  }
  
  return false
}

/**
 * 选择医院
 */
const selectHospital = (hospital: any) => {
  console.log('选择医院前:', selectedHospital.value)
  selectedHospital.value = hospital
  console.log('选择医院后:', selectedHospital.value)
  console.log('医院数据结构:', {
    id: hospital.id,
    key: hospital.key,
    name: hospital.name,
    title: hospital.title
  })

}

/**
 * 处理目录选择变化
 */
const onDirectoryChange = (data: any) => {
  console.log('ThreeLevelDirectoryPopup 收到变化事件:', data)
  
  // 根据 level 更新对应的项目
  if (data.level === 1) {
    currentLevel1Item.value = data.item
    currentLevel2Item.value = null
    currentSelectedItem.value = null
  } else if (data.level === 2) {
    currentLevel2Item.value = data.item
    currentSelectedItem.value = null
  } else if (data.level === 3) {
    currentSelectedItem.value = data.item
  }
  
  // 发送变化事件，格式化为统一格式
  const changeData = {
    currentItem: currentSelectedItem.value,
    level1Item: currentLevel1Item.value,
    level2Item: currentLevel2Item.value,
    hospital: selectedHospital.value
  }
  
  emit('change', changeData)
}

/**
 * 处理确认选择
 */
const handleConfirm = () => {
  if (props.showHospital && currentStep.value === 'hospital') {
    // 医院选择确认，进入科室选择步骤
    currentStep.value = 'department'
  } else if (currentStep.value === 'department') {
    // 科室选择确认，发送最终结果
    emit('confirm', {
      currentItem: currentSelectedItem.value,
      level1Item: currentLevel1Item.value,
      level2Item: currentLevel2Item.value,
      hospital: selectedHospital.value
    })
  }
}

/**
 * 处理关闭弹窗
 */
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

/**
 * 重置选择状态
 */
const resetSelection = () => {
  currentSelectedItem.value = null
  currentLevel1Item.value = null
  currentLevel2Item.value = null
  selectedHospital.value = null
  currentStep.value = props.showHospital ? 'hospital' : 'department'
}

/**
 * 加载医院列表
 */
const loadHospitalList = async () => {
  if (hospitalLoading.value) return // 防止重复加载
  
  hospitalLoading.value = true
  try {
    // 使用项目中已有的医院 API 路径，参考 HospitalDepartmentProjectSelector
    const res = await request.get(
      '/nurse_hospital/nurseHospital/loadTreeChildren?pid=0',
      {},
      { useErrMsg: true }
    )
    const records = res.success || []
    hospitalList.value = records || []
    console.log('医院列表加载成功:', hospitalList.value)
  } catch (error) {
    console.error('加载医院列表失败:', error)
    // 提供默认的医院列表作为备选
    hospitalList.value = [
      {
        id: '1',
        name: '南宁安好护理站',
        address: '广西南宁市',
        key: '1'
      },
      {
        id: '2', 
        name: '华声护理站',
        address: '广西南宁市',
        key: '2'
      }
    ]
  } finally {
    hospitalLoading.value = false
  }
}

// 监听弹窗关闭，重置选择状态
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    resetSelection()
  } else {
    // 弹窗打开时，如果需要显示医院选择，先加载医院列表
    if (props.showHospital) {
      loadHospitalList()
    } else {
      // 弹窗打开时，延迟检查是否有默认选中项
      setTimeout(() => {
        checkDefaultSelection()
      }, 300)
    }
  }
})

/**
 * 检查默认选中项
 */
const checkDefaultSelection = async () => {
  await nextTick()
  
  // 如果目录组件已经加载完成且有默认选中项，但没有触发事件
  // 这里可以手动检查并设置状态
  console.log('检查默认选中项:', {
    currentSelectedItem: currentSelectedItem.value,
    level1Item: currentLevel1Item.value,
    level2Item: currentLevel2Item.value
  })
  
  // 如果目录组件有默认选中项但没有触发事件，手动触发
  if (directoryRef.value && !currentSelectedItem.value) {
    try {
      // 尝试从目录组件获取当前选中状态
      const directoryComponent = directoryRef.value
      if (directoryComponent && typeof directoryComponent.getCurrentSelection === 'function') {
        const selection = directoryComponent.getCurrentSelection()
        console.log('获取目录组件选择状态:', selection)
        
        if (selection && selection.level3Item) {
          console.log('手动设置默认选中项:', selection)
          // 先设置前两级，再设置第三级
          if (selection.level1Item) {
            onDirectoryChange({ level: 1, item: selection.level1Item })
          }
          if (selection.level2Item) {
            onDirectoryChange({ level: 2, item: selection.level2Item })
          }
          onDirectoryChange({ level: 3, item: selection.level3Item })
        }
      }
    } catch (error) {
      console.log('无法获取目录组件状态:', error)
    }
  }
}

// 暴露方法给父组件
defineExpose({
  resetSelection,
  directoryRef
})
</script>

<style scoped lang="scss">
.directory-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    position: relative;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      position: absolute;
      right: 32rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40rpx;
      color: #999;
      cursor: pointer;
      
      &:active {
        opacity: 0.6;
      }
    }
  }
  
  .popup-content {
    flex: 1;
    overflow-y: auto;
  }
  
  .popup-footer {
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    border-top: 1rpx solid #f0f0f0;
    
    .confirm-btn {
      width: 100%;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.selection-info {
  padding: 24rpx;
  text-align: center;
  
  .selected-item {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
  }
}

.hospital-selection {
  padding: 24rpx;
  
  .loading-container, .empty-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200rpx;
    
    .loading-text, .empty-text {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .hospital-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }
  
  .hospital-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;
    
    &.selected {
      background: #e3f2fd;
      border-color: #3b82f6;
    }
    
    &:active {
      opacity: 0.8;
    }
    
    .hospital-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      
      .hospital-name {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
      }
      
      .hospital-address {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .selected-icon {
      margin-left: 16rpx;
    }
  }
}
</style>
